//
//  NSObject+Extension.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/9.
//  Copyright © 2015年 王先强. All rights reserved.
//  获取类中的所有属性

import Foundation

extension NSObject {
    // 获取属性
    func getProperties(clazz: AnyClass) -> [String] {
        
        var count: UInt32 = 0
        let ivars:  UnsafeMutablePointer<Ivar> = class_copyIvarList(clazz, &count)
        
        var propertyNames = [String]()
        for var i = 0; i < Int(count); i++ {
            let ivar = ivars[i]
            let ivarName = ivar_getName(ivar)
            let pName = NSString(UTF8String: ivarName) as! String
            propertyNames.append(pName)
        }
        return propertyNames
    }
    
    // 属性描述
    func descriptionFromClazz(clazz: AnyClass) -> String {
        let keys = getProperties(clazz)
        return (dictionaryWithValuesForKeys(keys) as NSDictionary).description
    }
    
    // 归档
    func encodeObj(obj: AnyObject, coder: NSCoder) {
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties {
            coder.encodeObject(obj.valueForKey(p), forKey: p)
        }
    }
    
    // 解归档
    func decodeObj(obj: AnyObject, coder: NSCoder) {
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties {
            if let value = coder.decodeObjectForKey(p) {
                obj.setValue(value, forKey: p)
            }
        }
    }}